<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use App\Models\FinancialStatementsLog;
use App\Models\Order;
use App\Models\WithdrawalLog;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\MessageBag;
class WithdrawalLogController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '申请提现';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new WithdrawalLog());
        $grid->disableExport();//禁止导出
        $grid->header(function () {
            $userid = auth()->user()->id ?? 0;
            $surplus = (new AdminUser())->where([['id','=',$userid]])->first();//value("surplus");
//            $wait = (new FinancialStatementsLog())
//                ->from("c_financial_statements_logs as f_log")
//                ->join("c_orders as order",'order.id','=','f_log.order_id')
//                ->where([['order.pay_status','=',1],['order.order_status','=',0],['f_log.work_id','=',$userid],['f_log.divide_type','=',2]])
//                ->sum("money");
            return '<div style="text-align: left;font-size: 13px;">可提现金额:'.$surplus->surplus.'&nbsp;&nbsp;&nbsp;待结算金额:'.$surplus->wait_surplus.'</div>';
        });
        $grid->tools(function (Grid\Tools $tools){
            $tools->append('<div class="btn-group pull-right grid-create-btn" style="margin-right: 10px">
            <a href="'.url('admin/alipayadd').'" class="btn btn-sm btn-success" title="绑定支付宝账号">
                <span class="hidden-xs">&nbsp;&nbsp;绑定支付宝账号</span>
            </a>
        </div>'
            );
        });
        // 去掉筛选工具
        $grid->tools(function (Grid\Tools $tools) {
            $tools->disableFilterButton();
        });
        $grid->disableRowSelector();
        $grid->actions(function ($actions) {
            // 去掉查看
//            $actions->disableView();
            $actions->disableDelete();
            $actions->disableEdit();
        });
        $userid = auth()->user()->id ?? 0;
        $where [] = ['user_id', '=', $userid];
        $grid->model()->where($where)->orderByDesc('id');
        $grid->column('id', __('Id'));
        $grid->column('money', __('金额'));
        $grid->column('alipay_account', __('支付宝账号'));
        $grid->column('alipay_name', __('支付宝名称'));
//        $grid->column('user_id', __('User id'));
        $grid->column('type', __('类型'))->using([
            1 => '工作室',
            2 => '用户',
            3 => '供应商',
        ]);
        $grid->column('status', __('状态'))->using([
            0 => '待审核',
            1 => '已提现',
            2 => '已驳回',
        ])->dot([
            0 => 'danger',
            1 => 'success',
            2 => 'danger',
        ]);;
        $grid->column('adminuser.name', __('操作人'));
        $grid->column('operation_time', __('操作时间'));
//        $grid->column('sn', __('Sn'));
        $grid->column('created_at', __('申请时间'));
//        $grid->column('updated_at', __('Updated at'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(WithdrawalLog::findOrFail($id));
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();
            $tools->disableEdit();
        });
        $show->field('id', __('Id'));
        $show->field('money', __('金额'));
//        $show->field('user_id', __('User id'));
//        $show->field('type', __('Type'));
        $show->field('status', __('提现状态'))->as(function () {
            $option = [
                0 => '待审核',
                1 => '已提现',
                2 => '已驳回'
            ];
            return $option[$this->status] ?? '';
        });

//        $show->field('operation_uid', __('Operation uid'));
//        $show->field('operation_time', __('Operation time'));
//        $show->field('sn', __('Sn'));
        $show->field('created_at', __('申请时间'));
//        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new WithdrawalLog());

        $form->decimal('money', __('提现金额'));
        $userid = auth()->user()->id ?? 0;
        $form->hidden('user_id', __('User id'))->value($userid);
        $form->hidden('type', __('Type'))->value(3);
        $form->saving(function ($form) {
            $userid = auth()->user()->id ?? 0;
            $admin_user = (new AdminUser())->where([['id', '=', $userid]])->first();
            if(!$admin_user->alipay_account || !$admin_user->alipay_name){
                $error = new MessageBag([
                    'title' => '温馨提示',
                    'message' => '请先添加支付宝账号后再申请提现!',
                ]);
                return back()->with(compact('error'));
            }
            $money = $admin_user->surplus;
            $exist =   (new WithdrawalLog())->where([['user_id','=',$userid],['type','=',3],['status','=',0]])->first();
            if($exist){
                $error = new MessageBag([
                    'title' => '温馨提示',
                    'message' => '您已存在提现记录,待工作人员审核后,再次提交!',
                ]);
                return back()->with(compact('error'));
            }
            $form->model()->setAttribute('name', $admin_user->name);
            $form->model()->setAttribute('alipay_account', $admin_user->alipay_account);
            $form->model()->setAttribute('alipay_name', $admin_user->alipay_name);
            $after_price = (new Order())->getMoneyForAfterSalesPeriod($userid,3);//售后金额和7天退货时间
            if ($money - $after_price < $form->money) {
                $error = new MessageBag([
                    'title' => '温馨提示',
                    'message' => '您有工作室在售后订单或未过7天保障期订单,提现金额不足!',
                ]);
                return back()->with(compact('error'));
            }
            if ($money < $form->money) {
                $error = new MessageBag([
                    'title' => '温馨提示',
                    'message' => '输入金额必须小于账号金额',
                ]);
                return back()->with(compact('error'));
            }
            if ($form->money < 1) {
                $error = new MessageBag([
                    'title' => '温馨提示',
                    'message' => '输入金额不能小于1!',
                ]);
                return back()->with(compact('error'));
            }
        });
        $form->saved(function (Form $form) {
            $userid = auth()->user()->id ?? 0;
            (new AdminUser())->where([['id', '=', $userid]])->decrement("surplus",$form->money);
        });
//        $form->number('status', __('Status'));
//        $form->number('operation_uid', __('Operation uid'));
//        $form->datetime('operation_time', __('Operation time'))->default(date('Y-m-d H:i:s'));
//        $form->text('sn', __('Sn'));

        return $form;
    }
}
